﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.Allcate;

namespace SmartProduction.Write.API.Application.CommandHandlers.Allcate
{
    /// <summary>
    /// 调拨单添加 命令处理
    /// </summary>
    public class AllcateCreateCommandHandler:IRequestHandler<AllcateCommand,APIResult<object>>
    {
        /// <summary>
        /// 调拨单仓储
        /// </summary>
        private readonly IBaseRepository<Allocate> allcateRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="allcateRep">调拨单仓储</param>
        /// <param name="mapper">映射</param>
        public AllcateCreateCommandHandler(IBaseRepository<Domain.yjh.Allocate> allcateRep,IMapper mapper)
        {
            this.allcateRep = allcateRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<APIResult<object>> Handle(AllcateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            var entity = mapper.Map<Allocate>(request);
            var r = allcateRep.AddAsync(entity).Result;

            if (r > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = r;
            }
            else
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = r;
            }

            return await Task.FromResult(result);
        }
    }
}
